#!/usr/bin/env python
#coding:utf-8

import struct 
import binascii
import serial
import math
from datetime import datetime



class HDDiscoveryQ2:
	def __init__(self):
		self.q2 = struct.Struct('<3sbhHHBHB')
		self.type	  = 'dq2'
		self.move_mode = 0
		self.start_dir = 0
		self.speed	 = 0
		self.time	  = 0
		self.unused	= 0
		self.verge	 = 0
		self.end	   = 0xaa

	def pack(self):
		data = self.q2.pack( self.type, self.move_mode, \
							 self.start_dir, self.speed, self.time, \
							 self.unused, 0, 0 )
		
		checksum = 0
		for i in range( len(data) ):
			x, = struct.unpack('<B', data[i])
			checksum+=int(x)
		self.verge = checksum
		return self.q2.pack( self.type, self.move_mode, \
							 self.start_dir, self.speed, self.time, \
							 self.unused, self.verge, self.end )


if __name__ == '__main__':
	global q2
	global serial_port

	q2 = HDDiscoveryQ2()
	q2.move_mode = 0
	q2.start_dir = 90
	q2.speed	 = 1000
	q2.time	     =1000
	
	print 'size of each command:', q2.q2.size
	
	#f = open( 'test' , "wb" )
	#f.write( q2.pack() )
	
	interval = 9  #in millisecond
	total = 0	   #max >=1000ms (1s)
	
	serial_port = serial.Serial( '/dev/ttyUSB0', 9600, timeout=2 )
	
	before = datetime.now()
	print before
	
	while True:
		duration = datetime.now() - before

		if total >=90: 
			break
			
		if ( duration.microseconds/1000 ) > interval:
			serial_port.write( q2.pack() )
			before = datetime.now()
			print 'aa:', before
			total += interval
			
	print 'times:%d' % ( total/interval )
	while True:
		line = serial_port.readline()
		print line

